package dyn 
{
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	/**
	 * ...
	 * @author Excel Excel
	 */
	public class DTiler implements ITiler
	{
		private var xmldata:XML;
		private var bmp:Object;
		private var fms:Vector.<TileFamily>;
		private var map:TileFamily;
		private var omap:TileFamily;
		private var _done:Boolean;
		private var _error:Boolean;
		
		public function DTiler() 
		{
			_done = false;
			_error = false;
			fms = new Vector.<TileFamily>();
			bmp = new Object();
			map = new TileFamily(0);
			omap = new TileFamily(0);
			xmldata = new XML();
			var xmlURL:URLRequest = new URLRequest('tiles.xml');
			var xmlLoader:URLLoader = new URLLoader(xmlURL);
			xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
			xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, xmlLoadError);
		}
		
		
		
		
		/* INTERFACE ITiler */
		
		public function getTile(color:uint, seed:uint = 0):BitmapData
		{
			if (bmp[color])
				return bmp[color].GetTile(seed);
			return bmp[0].GetTile(seed);
		}
		
		public function getMap(level:uint = 0):BitmapData
		{
			return map.GetDirect(level);
		}
		public function getOMap(level:uint = 0):BitmapData
		{
			return omap.GetDirect(level);
		}
		
		
		function xmlLoaded(event:Event)
		{
			xmldata = XML(event.target.data);
			for (var i:int = 0; i < xmldata.families.child("*").length();i++ )
			{
				var c:uint = parseInt(xmldata.families.family[i].@hex);
				bmp[c] = new TileFamily(c);
				fms.push(bmp[c]);
				for (var j:int = 0; j < xmldata.families.family[i].child("*").length(); j++)
				{
					var k:int = 1;
					if (xmldata.families.family[i].tile[j].@weight)
					{
						k = parseInt(xmldata.families.family[i].tile[j].@weight);
					}
					bmp[c].AddTile(xmldata.families.family[i].tile[j], k);
				}

			}
			for (var k:int = 0; k < xmldata.levels.child("*").length(); k++)
			{
				map.AddTile(xmldata.levels.level[k].@terrain, 0);
				omap.AddTile(xmldata.levels.level[k].@objects, 0);
			}
			_done = true;
			//trace(xmldata.tilepath);
			
		}
		
		function xmlLoadError(event:IOErrorEvent)
		{
			_error = true;
			trace (event.text);
			throw (event.text);
		}
		
		public function get done () : Boolean
		{
			
			for (var i:int = 0; i < fms.length; i++)
			{
				if (!fms[i].done) return false;
			}
			return _done && map.done && omap.done;
		}
		
		public function get error () : Boolean
		{
			for (var i:int = 0; i < fms.length; i++)
			{
				if (fms[i].error) 
					return true;
			}
			return _error || map.error || omap.error;
		}
		
		
		
	}

}